package br.ufrgs.dbproject;

import java.util.Stack;

import br.ufrgs.dbproject.idgenerator.ID;

/**
 * Abstraction of an ID generation context for XML elements.
 * 
 * <p>
 * <ul>
 * <li>A context is composed by a stack which holds the generated IDs until a specific time, and the stack size gives the current deep in the XML tree being processed.</li>
 * <li>Also, a context holds the last generated ID until now.</li>
 * </ul>
 * </p>
 * 
 * @author diego
 *
 * @param <T> ID type which must implement the interface {@link ID}
 */
public class Context<T extends ID> {

	/**
	 * Holds the IDs of opened XML elements.
	 * 
	 * <p>
	 * For each start tag, an ID is generated and pushed into the stack. This ID is popped from the
	 * stack when an end tag is found.
	 * </p>
	 */
	private Stack<T> stack;
	
	/**
	 * The last generated ID which not necessary is the top of the stack.
	 */
	private T lastGeneratedID;

	public Context(T emptyID) {
		this.stack = new Stack<T>();
		this.lastGeneratedID = emptyID;
	}
	
	public void saveID(T id) {
		stack.push(id);
		lastGeneratedID = id;
	}
	
	public void forgetLastSavedID() {
		if (!stack.isEmpty()) {
			lastGeneratedID = stack.pop();
		}
	}
	
	public T peekID() {
		return stack.peek();
	}
	
	public boolean isEmpty() {
		return stack.isEmpty();
	}

	public int getSize() {
		return stack.size();
	}

	public void setIDsStack(Stack<T> stack) {
		this.stack = stack;
	}
	
	public T getLastSavedID() {
		return lastGeneratedID;
	}
}
